package com.jn.server;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

public class StudentAdapter extends ArrayAdapter<Student> {

    private List<Student> internalList;
    private LayoutInflater inflater;
    private int resourceLayout;

    public StudentAdapter(Context context, int resource, List<Student> objects) {
        super(context, resource, objects);
        this.internalList = new ArrayList<>(objects);
        this.resourceLayout = resource;
        inflater = LayoutInflater.from(context);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = inflater.inflate(resourceLayout, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.id = convertView.findViewById(R.id.i_index) ;
            viewHolder.studentName = convertView.findViewById(R.id.i_name);
            viewHolder.studentNumber = convertView.findViewById(R.id.i_number);
            viewHolder.studentGrade = convertView.findViewById(R.id.i_grade);
            viewHolder.studentAge = convertView.findViewById(R.id.i_age);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        Student student = internalList.get(position);
        if (student != null) {
            viewHolder.id.setText(String.valueOf(position+1));
            viewHolder.studentName.setText(student.getName());
            viewHolder.studentNumber.setText(String.valueOf(student.getNumber()));
            viewHolder.studentGrade.setText(student.getGrade());
            viewHolder.studentAge.setText(String.valueOf(student.getAge()));
        }

        return convertView;
    }

    @Override
    public int getCount() {
        return internalList.size();
    }

    @Override
    public Student getItem(int position) {
        return internalList.get(position);
    }

    public void clear() {
        internalList.clear();
        notifyDataSetChanged();
    }

    public void addAll(List<Student> students) {
        internalList.addAll(students);
        notifyDataSetChanged();
    }

    private static class ViewHolder {
        TextView id ;
        TextView studentName;
        TextView studentNumber;
        TextView studentGrade;
        TextView studentAge;
    }
}